package com.example.wiki.controller;

import com.alibaba.fastjson.JSON;
import com.example.wiki.common.vo.CommonVo;
import com.example.wiki.common.vo.PageVo;
import com.example.wiki.req.UserLoginReq;
import com.example.wiki.req.UserQueryReq;
import com.example.wiki.req.UserResetPasswordReq;
import com.example.wiki.req.UserSaveReq;
import com.example.wiki.service.UserService;
import com.example.wiki.util.SnowFlake;
import com.example.wiki.vo.UserLoginVo;
import com.example.wiki.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SnowFlake snowFlake;//使用雪花算法生成token


    @GetMapping("list")
    public CommonVo<PageVo<UserVo>> getList(@Valid UserQueryReq userQueryReq){//@Valid 检验
        PageVo<UserVo> pageVo = userService.list(userQueryReq);
        CommonVo<PageVo<UserVo>> commonVo = new CommonVo<>();
        commonVo.setContent(pageVo);
        return commonVo;
    }

    @PostMapping("save")
    public CommonVo save( @Valid @RequestBody  UserSaveReq userSaveReq){

        CommonVo commonVo = new CommonVo<>();

         userService.save(userSaveReq);

        return commonVo;
    }

    @DeleteMapping("delete/{id}")
    public CommonVo delete(@PathVariable Long id){

        CommonVo commonVo = new CommonVo<>();

        userService.remove(id);

        return commonVo;
    }

    @PostMapping("resetPassword")
    public CommonVo resetPassword(@Valid @RequestBody UserResetPasswordReq userResetPasswordReq){

        CommonVo commonVo = new CommonVo<>();

        userService.resetPassword(userResetPasswordReq);

        return commonVo;
    }

    @PostMapping("login")
    public CommonVo<UserLoginVo> login( @RequestBody @Valid UserLoginReq userLoginReq){

        CommonVo<UserLoginVo> commonVo = new CommonVo<>();

        UserLoginVo userLoginVo = userService.login(userLoginReq);

        String token = String.valueOf(snowFlake.nextId());
        //返回token
        userLoginVo.setToken(token);

        System.out.println(token);
        //存储token用于验证
        redisTemplate.opsForValue().set(token, JSON.toJSONString(userLoginVo) ,  3600 * 24, TimeUnit.SECONDS);


        System.out.println(redisTemplate.opsForValue().get(token));

        commonVo.setContent(userLoginVo);

        return commonVo;
    }

    @GetMapping("logout/{token}")
    public CommonVo delete(@PathVariable String token){

        CommonVo commonVo = new CommonVo<>();

        redisTemplate.delete(token);

        return commonVo;
    }



}
